//
//  PGPluginBLEPrinter.m
//  HBuilder-Hello
//
//  Created by hennychen on 8/3/17.
//  Copyright © 2017 DCloud. All rights reserved.
//

#import "PGPluginBLEPrinter.h"
#import "PDRCoreAppFrame.h"
#import "H5WEEngineExport.h"
#import "PDRToolSystemEx.h"
// 扩展插件中需要引入需要的系统库
#import <LocalAuthentication/LocalAuthentication.h>
#import "NSMutableDictionary+NotNull.h"


@implementation PGPluginBLEPrinter


#pragma mark 这个方法在使用WebApp方式集成时触发，WebView集成方式不触发

/*
 * WebApp启动时触发
 * 需要在PandoraApi.bundle/feature.plist/注册插件里添加autostart值为true，global项的值设置为true
 */
- (void) onAppStarted:(NSDictionary*)options{
    
    NSLog(@"5+ WebApp启动时触发");
    // 可以在这个方法里向Core注册扩展插件的JS
    
}

// 监听基座事件事件
// 应用退出时触发
- (void) onAppTerminate{
    //
    NSLog(@"APPDelegate applicationWillTerminate 事件触发时触发");
}

// 应用进入后台时触发
- (void) onAppEnterBackground{
    //
    NSLog(@"APPDelegate applicationDidEnterBackground 事件触发时触发");
}

// 应用进入前天时触发
- (void) onAppEnterForeground{
    //
    NSLog(@"APPDelegate applicationWillEnterForeground 事件触发时触发");
}

// 调用指纹解锁
- (void)AuthenticateUser:(PGMethod*)command
{
    if (nil == command) {
        return;
    }
    BOOL isSupport = false;
    NSString* pcbid = [command.arguments objectAtIndex:0];
    NSError* error = nil;
    NSString* LocalReason = @"HBuilder指纹验证";
    
    // Touch ID 是IOS 8 以后支持的功能
    if ([PTDeviceOSInfo systemVersion] >= PTSystemVersion8Series) {
        LAContext* context = [[LAContext alloc] init];
        if ([context canEvaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics error:&error]) {
            isSupport = true;
            [context evaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics localizedReason:LocalReason reply:^(BOOL success, NSError * _Nullable error) {
                PDRPluginResult * pResult = nil;
                
                if (success) {
                    
                    pResult = [PDRPluginResult resultWithStatus: PDRCommandStatusOK messageAsDictionary:@{@"state":@(0), @"message":@"成功"}];
                }
                else{
                    NSDictionary* pStringError = nil;
                    switch (error.code) {
                        case LAErrorSystemCancel:
                        {
                            pStringError = @{@"state":@(-1), @"message":@"系统取消授权(例如其他APP切入)"};
                            break;
                        }
                        case LAErrorUserCancel:
                        {
                            pStringError = @{@"state":@(-2), @"message":@"用户取消Touch ID授权"};
                            break;
                        }
                        case LAErrorUserFallback:
                        {
                            pStringError  = @{@"state":@(-3), @"message":@"用户选择输入密码"};
                            break;
                        }
                        case LAErrorTouchIDNotAvailable:{
                            pStringError  = @{@"state":@(-4), @"message":@"设备Touch ID不可用"};
                            break;
                        }
                        case LAErrorTouchIDLockout:{
                            pStringError  = @{@"state":@(-5), @"message":@"Touch ID被锁"};
                            break;
                        }
                        case LAErrorAppCancel:{
                            pStringError  = @{@"state":@(-6), @"message":@"软件被挂起取消授权"};
                            break;
                        }
                        default:
                        {
                            pStringError  = @{@"state":@(-7), @"message":@"其他错误"};
                            break;
                        }
                    }
                    pResult = [PDRPluginResult resultWithStatus:PDRCommandStatusError messageAsDictionary:pStringError];
                    
                }
                
                [self toCallback:pcbid withReslut:[pResult toJSONString]];
            }];
        }
        else{
            NSDictionary* pStringError = nil;
            switch (error.code) {
                case LAErrorTouchIDNotEnrolled:
                {
                    pStringError  = @{@"state":@(-11), @"message":@"设备Touch ID不可用"};
                    break;
                }
                case LAErrorPasscodeNotSet:
                {
                    pStringError  = @{@"state":@(-12), @"message":@"用户未录入Touch ID"};
                    break;
                }
                    
                default:
                    break;
            }
        }
    }
    
    if (!isSupport) {
        PDRPluginResult* pResult = [PDRPluginResult resultWithStatus:PDRCommandStatusError messageAsString:@"Device Not Support"];
        [self toCallback:pcbid withReslut:[pResult toJSONString]];
    }
}
/**
 搜索蓝牙设备
 
 @param commands commands description
 */
- (void)searchBluetooth:(PGMethod*)commands
{
    if ( commands ) {
        
        NSLog(@"扫描蓝牙设备");
        peripheralsForScanArray = [[NSMutableArray alloc] init];
        scanUUIDArray = [[NSMutableArray alloc] init];
        
        [scanUUIDArray addObject:[[SKYBeaconScan alloc] initWithuuid:@"E2C56DB5-DFFB-48D2-B060-D0F5A71096E0" name:@"苹果默认"]];
        [scanUUIDArray addObject:[[SKYBeaconScan alloc] initWithuuid:@"FDA50693-A4E2-4FB1-AFCF-C6EB07647825" name:@"微信摇一摇"]];
        
        // 用于解密mac地址
        [SKYBeaconManager sharedDefaults].seekcyDecryptKey = @""; // 你的解密密钥
    
        [SKYBeaconManager sharedDefaults].scanBeaconTimeInterval = 1.2;
        [[SKYBeaconManager sharedDefaults] startScanForSKYBeaconWithDelegate:self uuids:scanUUIDArray distinctionMutipleID:NO isReturnValueEncapsulation:NO];
    }
}
#pragma mark - SKYBeaconManagerScanDelegate
- (void)skyBeaconManagerCompletionScanWithBeacons:(NSArray *)beascons error:(NSError *)error{
    
    if(error){
        
        if(error.code == SKYBeaconSDKErrorBlueToothPoweredOff){
//            [SVProgressHUD showErrorWithStatus:error.userInfo[@"error"] maskType:SVProgressHUDMaskTypeBlack];
//            [self callbackJavaScript:@"error" withMsg:@"SKYBeaconSDKErrorBlueToothPoweredOff"];
            
        }
    
        [self callbackJavaScript:@"error" withMsg:[NSString stringWithFormat:@"%ld",(long)error.code]];

        return;
    }
    NSMutableArray * arraydic = [NSMutableArray array];
    for (NSDictionary * model in beascons) {
        
        NSMutableDictionary * dic = [NSMutableDictionary dictionary];
        [dic setNoNullObject:model[modelTransitField_rssi] forKey:@"rssi"];
        [dic setNoNullObject:model[modelTransitField_major] forKey:@"major"];
        [dic setNoNullObject:model[modelTransitField_minor] forKey:@"minor"];
        [dic setNoNullObject:model[modelTransitField_macAddress] forKey:@"macAddress"];
        [dic setNoNullObject:model[modelTransitField_distance] forKey:@"distance"];
        [dic setNoNullObject:model[modelTransitField_battery] forKey:@"battery"];
        [dic setNoNullObject:model[modelTransitField_measuredPower] forKey:@"measuredPower"];

        if([NSJSONSerialization isValidJSONObject: dic]){
            [arraydic addObject:dic];
        }
        
    }    
    
    NSLog(@"--skyBeaconManagerCompletionScanWithBeacons--");
    NSLog(@"扫描到：%lu 个",(unsigned long)beascons.count);
    
    [peripheralsForScanArray removeAllObjects];
    [peripheralsForScanArray addObjectsFromArray:beascons];
    
    NSString *evalString = [NSString stringWithFormat:@"bluetoothCallBack(%@);",[self DataTOjsonString:arraydic]];
    [self.JSFrameContext stringByEvaluatingJavaScriptFromString:evalString];
    
    
}
/**
 关闭蓝牙
 
 @param commands <#commands description#>
 */
- (void)closeBluetooth:(PGMethod*)commands
{
    if ( commands ) {
        [[SKYBeaconManager sharedDefaults] stopScanSKYBeacon];
       
        [self callbackJavaScript:@"stop" withMsg:@"停止扫描"];
    }
}
-(NSString*)DataTOjsonString:(id)object
{
    NSString *jsonString = nil;
    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:object
                                                       options:NSJSONWritingPrettyPrinted // Pass 0 if you don't care about the readability of the generated string
                                                         error:&error];
    if (! jsonData) {
        NSLog(@"Got an error: %@", error);
    } else {
        jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    }
    return jsonString;
}
-(void)callbackJavaScript:(NSString *)code withMsg:(NSString *)msg{
    NSLog(@"code is %@-- msg %@",code,msg);
    NSDictionary * dicresponse = @{@"code":code,@"msg":msg};
    
    NSString *evalString = [NSString stringWithFormat:@"bluetoothCallBack(%@);",[self DataTOjsonString:dicresponse]];
    [self.JSFrameContext stringByEvaluatingJavaScriptFromString:evalString];
}
@end
